const express = require('express');
const router = express.Router();
const { resExtra } = require('../../../utils/utils.resextra')
const jwt = require('jsonwebtoken')
const UserSrevice = require("../../../service/user.service");

router.post("/", async (req, res, next) => {
  const { username, password } = req.body

  try {
    // 校验是否正确
    const data = await UserSrevice.login({ username, password })
    if (data) {
      // 生成jwt
      let token = jwt.sign(
        {
          username: data.username,
          role: data.role,
          villageId: data.villageId
        },
        process.env["SIGN_KEY"],
        {
          expiresIn: 3600 * 24 * 3 //3天
        }
      )
      res.sendResult(resExtra({ token: `Bearer ${token}`, role: data.role, username: data.username }))
    } else {
      res.sendResult(resExtra(null, 500, '用户名或密码错误'))
    }
  } catch (error) {
    next('服务器内部错误')
  }
});

module.exports = router;
